<template>
  <d2-container>
  <section class="vue-monitor">
    <el-row>
      <el-col :span="5" class="monitor-d monitor-tree-d">
        <el-scrollbar :style="'height:100%;width: 100%'">
          <area-tree @nodeChange="treeNodeChange"></area-tree>
        </el-scrollbar>
      </el-col>
      <el-col :span="19" class="monitor-d" style="padding-left:10px">
        <div>
          <el-form label-position="right" :model="dataForm" :inline="true">
            <el-form-item class="el-form-item--mini" label="分类能耗：">

              <el-select v-model="dataForm.energyType" @change="queryCollectType" style="width: 100px;" placeholder="请选择"  size="small">
                <el-option
                  v-for="(item, index) in meterTypeList" :key="index"
                  :label="item.paramValue"
                  :value="item.paramKey">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item  class="el-form-item--mini" label="采集项" label-width="60px">
              <el-select v-model="dataForm.collectType"  style="width: 140px;" placeholder="请选择"  size="small">
                <el-option
                  v-for="(item, index) in collectTypeList" :key="index"
                  :label="item.collectName"
                  :value="item.collectType">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item class="el-form-item--mini" label="日期: ">
              <el-date-picker
                v-model="dataForm.date"   size="small"
                type="datetimerange"  :picker-options="pickerOptions"
                range-separator="~"
                value-format="yyyy-MM-dd HH:mm:ss"
                start-placeholder="开始日期"
                end-placeholder="结束日期">
              </el-date-picker>
            </el-form-item>

            <el-form-item class="el-form-item--mini">
              <el-button
                class="filter-item"
                type="primary"
                icon="el-icon-search"
                size="small"
                @click="getPowerDataList"
              >查询</el-button>
              <el-button
                class="filter-item"
                type="primary"
                icon="el-icon-download"
                size="small"
                @click="exoprtData"
              >导出</el-button>
            </el-form-item>
          </el-form>
        </div>
        <div>
          <el-table
            :data="meterdataList"
            border
            v-loading="dataListLoading"
            style="width: 100%;overflow:visible;"
          >
            <el-table-column
              prop="bName"
              header-align="left"
              align="left"
              label="区域名称"
            ></el-table-column>
            <el-table-column
              prop="deviceName"
              header-align="left"
              align="left"
              label="计量器具名称"
            ></el-table-column>
            <el-table-column
              prop="startTime"
              header-align="left"
              align="left"
              label="起始时间"
            >
            </el-table-column>
            <el-table-column
              prop="startValue"
              header-align="left"
              align="left"
              :label="'起始数值('+currentUnit+')'"
            >
            </el-table-column>
            <el-table-column
              prop="endTime"
              header-align="left"
              align="left"
              label="截止时间"
            >
            </el-table-column>
            <el-table-column
              prop="endValue"
              header-align="left"
              align="left"
              :label="'截止数值('+currentUnit+')'"
            >
            </el-table-column>
            <el-table-column
              prop="addValue"
              header-align="left"
              align="left"
              :label="'差值('+currentUnit+')'"
            >
            </el-table-column>
          </el-table>

        </div>
      </el-col>
    </el-row>
  </section>
  </d2-container>
</template>
<script>
import areaTree from './compont/area_tree';
import * as Util from "@/utils";
import Config from "@/utils/config"
export default {
  /*
  * 环比分析
  **/
  data() {
    return {
      meterdataList:[],
      buildList:'',
      dataTypeDesc:'当日',
      lastDataTypeDesc:'昨日',
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now();
        }
      },
      Config:Config,
      meterTypeList:[],
      dataForm: {
        date: '',
        energyType:'',
        collectType:'',
        subEnergyType:'',//分项选择值
      },
      currentUnit:'',
      dataListLoading:false,
    }
  },
  components:{
    areaTree
  },
  computed:{
    containerHeight() {
      return Util.getClientHeight() - 143;
    }
  },
  watch: {
    'dataForm.energyType':function(newV,oldV){
      this.currentUnit = this.meterTypeList.find(item => item.paramKey == newV).paramExt;
    },
  },
  methods: {
    /**
     * 获取采集分项
     */
    queryCollectType() {
      let params = {
        'meterType': this.dataForm.energyType ,
        'state': '1' ,
        'cumulativeType':'1',
        "customerId":this.$util.cookies.get('customer_id'),
        'page': 1,
        'limit': 10000,
      }
      this.$api.okhttp({
        url: this.$http.adornUrl('/ecs/ecscollectitem/list'),
        method: 'get',
        params: this.$http.adornParams(params)
      }).then((data) => {
        if (data && data.code === 0) {
          this.collectTypeList = data.page.list
          this.dataForm.collectType = data.page.list[0].collectType;
          if(data.page.list[0].collectUnit !=='') {
            this.unit = data.page.list[0].collectUnit;
          }
        } else {
          this.collectTypeList = []
        }
      });
    },
    /**
     * 集抄报表
     * */
    getPowerDataList() {
      if( this.dataForm.energyType =='' || this.buildList =='') {
        return
      }

      this.dataListLoading = true;
      this.$api.okhttp({
        url:this.$http.adornUrl('/eas/collectingReport/list'),
        method: "post",
        data: this.$http.adornParams(
          {
            buildingIds: this.buildList,
            dateRange: this.dataForm.date,
            meterType: this.dataForm.energyType,
            subEnergyType: this.dataForm.collectType,
            customerId: this.$util.cookies.get("customer_id"),
            projectId:this.$util.cookies.get("cuuren_projectId")
          }
        )
      }).then((data) => {
        if (data && data.code === 0) {
          this.meterdataList = data.data;
        }
        this.dataListLoading = false;
      })
    },
    getDateStr(){
      return (this.dataForm.date&&this.dataForm.date!="")?this.formarDate(this.dataForm.dateType,new Date(this.dataForm.date)):''
    },
    formarDate(type, date) {
      return Util.dateFormat(Config.searchDate.find(item => item.date == type).format, date)
    },
    exoprtData(){
      // 导出数据
      let header=['区域名称','计量器具名称','起始时间','起始数值('+this.currentUnit+')','截止时间','截止数值('+this.currentUnit+')','差值('+this.currentUnit+')'];
      let props=['bName','deviceName','startTime','startValue','endTime','endValue','addValue']
      let fileName=` 集抄报表(${ this.meterTypeList.find(item=>item.paramKey==this.dataForm.energyType).paramValue})${this.dataForm.date}统计`
      this.export2Excel(header,props,fileName,this.meterdataList);
    },
    export2Excel(tH, fi, fiNa, dataList) {
      var tHeader = tH
      var filterVal = fi
      var fileName = fiNa
      require.ensure([], () => {
        const { export_json_to_excel } = require('@/utils/Export2Excel.js')
        const list = JSON.parse(JSON.stringify(dataList));
        // let sumVal = list.reduce(function (total, currentValue, currentIndex, arr) {
        //   return total + currentValue.val;
        // }, 0);
        // list.push({
        //   "buildingName":'合计',
        //   "val":sumVal
        // })
        const data = this.formatJson(filterVal, list)
        export_json_to_excel(tHeader, data, fileName)
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => v[j]))
    },
    changeDateType() {
      if (this.dataForm.dateType === 'date') {
        this.dataTypeDesc = '当日'
        this.lastDataTypeDesc= '昨日'

      } else if (this.dataForm.dateType === 'month') {
        this.dataTypeDesc = '当月'
        this.lastDataTypeDesc= '上月'
      }
    },
    treeNodeChange(data){
      this.buildList = data
      this.getPowerDataList()
    },
    queryStatic(type,paramValue,callback) {
      let params = {
        'code': type ,
        "customerId":this.$util.cookies.get('customer_id')
      }
      if(paramValue){
        Object.assign(params,{paramValue,paramValue});
      }
      this.$api.okhttp({
        url: this.$http.adornUrl('/sys/sysstaticdata/getList'),
        method: 'get',
        params: this.$http.adornParams(params)
      }).then((data) => {
        if(callback){
          callback(data);
        }
      });
    },

  },
  computed: {
    containerHeight() {
      return Util.getClientHeight() - 163;
    },
    bottomChartHeight(){
      return Util.getClientHeight() - 298;
    }
  },
  created() {
    this.dataForm.date=[Util.dateFormat('YYYY-mm-dd',new Date())+" 00:00:00",Util.dateFormat('YYYY-mm-dd',new Date())+ " 23:59:59"];
    this.$nextTick(()=>{
      this.queryStatic("METER_TYPE",null,data=>{
        if (data && data.code === 0) {
          this.meterTypeList = data.page
          this.dataForm.energyType = data.page[0].paramKey;
          this.currentUnit = data.page[0].paramExt;
          this.queryCollectType()
        } else {
          this.meterTypeList = []
        }
        this.$nextTick(()=> {
          this.getPowerDataList()
        });
      });
    })
  }
}

</script>
<style scoped lang="scss">
  @import "../../assets/scss/_variables";
.vue-monitor {
  min-width: 900px;
}

.vue-monitor .el-row {
  width: 100%;
  display: flex;
  align-items: flex-start;
}
.vue-monitor .monitor-d{
  // box-shadow: 0px 0px 1px 1px #f7f6f6;
}
.vue-monitor .monitor-tree-d {
    /*position: absolute;*/
    height: 100%;
    top: 0;
    /*right: 0;*/
}




/*清除浮动代码*/

.clearfloat:after {
  display: block;
  clear: both;
  content: "";
  visibility: hidden;
  height: 0
}

.clearfloat {
  zoom: 1
}


</style>
